from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.core.paginator import Paginator
from django.contrib import messages
from django.db.models import Count, Avg, Max, Min

from .models import MonitoringCategory, MonitoringData
from .forms import MonitoringCategoryForm, MonitoringDataForm

@login_required
def dashboard(request):
    """仪表盘视图"""
    # 获取统计数据
    total_categories = MonitoringCategory.objects.count()
    total_data = MonitoringData.objects.count()
    normal_count = MonitoringData.objects.filter(status='normal').count()
    warning_count = MonitoringData.objects.filter(status='warning').count()
    danger_count = MonitoringData.objects.filter(status='danger').count()
    
    # 获取最近的监测数据
    recent_data = MonitoringData.objects.select_related('category').order_by('-measured_at')[:10]
    
    context = {
        'total_categories': total_categories,
        'total_data': total_data,
        'normal_count': normal_count,
        'warning_count': warning_count,
        'danger_count': danger_count,
        'recent_data': recent_data,
    }
    return render(request, 'monitoring/dashboard.html', context)

@login_required
def category_list(request):
    """监测类别列表视图"""
    categories = MonitoringCategory.objects.annotate(data_count=Count('data'))
    return render(request, 'monitoring/category_list.html', {'categories': categories})

@login_required
def category_create(request):
    """创建监测类别视图"""
    if request.method == 'POST':
        form = MonitoringCategoryForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, '监测类别创建成功')
            return redirect('monitoring:category_list')
    else:
        form = MonitoringCategoryForm()
    
    return render(request, 'monitoring/category_form.html', {'form': form, 'title': '创建监测类别'})

@login_required
def category_update(request, pk):
    """更新监测类别视图"""
    category = get_object_or_404(MonitoringCategory, pk=pk)
    if request.method == 'POST':
        form = MonitoringCategoryForm(request.POST, instance=category)
        if form.is_valid():
            form.save()
            messages.success(request, '监测类别更新成功')
            return redirect('monitoring:category_list')
    else:
        form = MonitoringCategoryForm(instance=category)
    
    return render(request, 'monitoring/category_form.html', {'form': form, 'title': '更新监测类别'})

@login_required
def category_delete(request, pk):
    """删除监测类别视图"""
    category = get_object_or_404(MonitoringCategory, pk=pk)
    if request.method == 'POST':
        category.delete()
        messages.success(request, '监测类别删除成功')
        return redirect('monitoring:category_list')
    
    return render(request, 'monitoring/category_confirm_delete.html', {'category': category})

@login_required
def data_list(request):
    """监测数据列表视图"""
    data_list = MonitoringData.objects.select_related('category', 'created_by')
    
    # 筛选
    category_id = request.GET.get('category')
    status = request.GET.get('status')
    
    if category_id:
        data_list = data_list.filter(category_id=category_id)
    if status:
        data_list = data_list.filter(status=status)
    
    # 分页
    paginator = Paginator(data_list, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 获取所有类别，用于筛选
    categories = MonitoringCategory.objects.all()
    
    context = {
        'page_obj': page_obj,
        'categories': categories,
        'selected_category': category_id,
        'selected_status': status,
    }
    return render(request, 'monitoring/data_list.html', context)

@login_required
def data_create(request):
    """创建监测数据视图"""
    if request.method == 'POST':
        form = MonitoringDataForm(request.POST)
        if form.is_valid():
            data = form.save(commit=False)
            data.created_by = request.user
            data.save()
            messages.success(request, '监测数据创建成功')
            return redirect('monitoring:data_list')
    else:
        form = MonitoringDataForm()
    
    return render(request, 'monitoring/data_form.html', {'form': form, 'title': '创建监测数据'})

@login_required
def data_update(request, pk):
    """更新监测数据视图"""
    data = get_object_or_404(MonitoringData, pk=pk)
    if request.method == 'POST':
        form = MonitoringDataForm(request.POST, instance=data)
        if form.is_valid():
            form.save()
            messages.success(request, '监测数据更新成功')
            return redirect('monitoring:data_list')
    else:
        form = MonitoringDataForm(instance=data)
    
    return render(request, 'monitoring/data_form.html', {'form': form, 'title': '更新监测数据'})

@login_required
def data_delete(request, pk):
    """删除监测数据视图"""
    data = get_object_or_404(MonitoringData, pk=pk)
    if request.method == 'POST':
        data.delete()
        messages.success(request, '监测数据删除成功')
        return redirect('monitoring:data_list')
    
    return render(request, 'monitoring/data_confirm_delete.html', {'data': data})

@login_required
def data_detail(request, pk):
    """监测数据详情视图"""
    data = get_object_or_404(MonitoringData.objects.select_related('category', 'created_by'), pk=pk)
    return render(request, 'monitoring/data_detail.html', {'data': data})
